package rulebasedsystem;

import game.Board;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class RulesCollection {
	private static final String NAME_FILE_RULES = "rules.inf";
	private static final String SEPARADOR = "@";
	
	private ArrayList<SingleRule> rulesCollection;

	public ArrayList<SingleRule> getRulesCollection() {
		return rulesCollection;
	}

	public void setRulesCollection(ArrayList<SingleRule> rulesCollection) {
		this.rulesCollection = rulesCollection;
	}

	public RulesCollection() {
		this.rulesCollection = new ArrayList<SingleRule>();
		populateRules();
	}
	
	private void populateRules() {
		try {
			File file = new File(NAME_FILE_RULES);
			
			//Se arquivo existente, efetua a leitura
			if(file.isFile()) {
				List<String> list = new ArrayList<String>();
				
				InputStreamReader isr = new InputStreamReader(new FileInputStream(NAME_FILE_RULES), "ISO-8859-1");
				BufferedReader in = new BufferedReader(isr);
				
				while (in.ready()) {
					list.add(in.readLine());
				}
				
				in.close();
				isr.close();
				
				for(String linha : list) {
					String[] array = linha.split(SEPARADOR);
					Board board = new Board();
					
					int i = 0;
					for(int row = 1; row < Board.BOARD_SIZE; row++) {
						for(int column = 1; column < Board.BOARD_SIZE; column++) {
							board.setCellValue(row, column, Integer.parseInt(array[i]));
							i++;
						}
					}
					
					this.rulesCollection.add(new SingleRule(board, Integer.parseInt(array[i++]), Integer.parseInt(array[i++]), Integer.parseInt(array[i++])));
				}
			} else { //Caso contrario, cria-se o arquivo para a persistencia dos dados
				file.createNewFile();
			}
			
		} catch (Exception e) {
			System.out.println("Erro ao ler arquivo.");
		}
	}
	
	public void saveRules() {
		List<String> list = new ArrayList<String>();

		for(SingleRule singleRule : this.rulesCollection) {
			StringBuffer str = new StringBuffer();

			str.append(singleRule.getCurrentBoard().toStringArray(SEPARADOR));
			str.append(SEPARADOR);
			str.append(singleRule.getColor());
			str.append(SEPARADOR);
			str.append(singleRule.getRowToPlay());
			str.append(SEPARADOR);
			str.append(singleRule.getColumnToPlay());
			str.append(SEPARADOR);
			str.append(singleRule.getWeight());
			
			list.add(str.toString());
		}
		
		try {
			FileOutputStream fos = new FileOutputStream(NAME_FILE_RULES);
			String gravar = "";
			
			for(String str : list) {
				gravar += (str + "\n");
			}
			
			if(!gravar.equals("")) {
				fos.write(gravar.getBytes());
			}
			
			fos.close();
		} catch (Exception e) {
			System.out.println("Erro ao salvar arquivo.");
		}
	}
	
	public ArrayList<SingleRule> getRulesByBoard(Board board, int color){
		ArrayList<SingleRule> returnableRules = new ArrayList<SingleRule>();
		
		for (SingleRule currentRule : rulesCollection) {
			if((currentRule.getCurrentBoard()).equals(board) && (currentRule.getColor() == color)){
				returnableRules.add(currentRule);
			}
		}
		
		return returnableRules;
	}
	
	public void addRule(SingleRule rule){
		if(rule != null) {
			rulesCollection.add(rule);
		}
	}
	
	public void incrementWeightOfRule(SingleRule rule){
		for (SingleRule currentRule : rulesCollection) {
			if(currentRule.equals(rule)){
				currentRule.incrementRuleWeight();
			}
		}
	}
	
	public SingleRule getHighestWeightedRule(List<SingleRule> list){
		int highestWeight = 0;
		SingleRule highestWeightedRule = null;
		
		for (SingleRule currentRule : list) {
			if(highestWeight <= currentRule.getWeight()){
				highestWeight = currentRule.getWeight();
				highestWeightedRule = currentRule;
			}
		}
		
		return highestWeightedRule;
	}
}